package com.woyou.ui.activity;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import retrofit.RetrofitError;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.Info;
import com.woyou.bean.ShopItem;
import com.woyou.bean.rpc.ShopListReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.adapter.ShopListAdapter;
import com.woyou.ui.api.DefScrollListener;
import com.woyou.ui.api.DefScrollListener.DefScrollCallBack;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.component.fastscroll.FastScrollView;
import com.woyou.ui.component.fastscroll.IdleListDetector;
import com.woyou.ui.component.fastscroll.IdleListener;
import com.woyou.ui.fragment.IndexFragment_;
import com.woyou.utils.Task;

/**
 * 活动店铺
 * 
 * @author zhou.ni
 *
 */
@EActivity(R.layout.fm_specificshops)
public class SpecificShopsActivity extends BaseActivity {

	@ViewById(R.id.head_title)
	TextView headTitle;
	@ViewById(R.id.specific_hintView)
	ErrorHintView mErrorHintView;
	@ViewById(R.id.specific_fastscroll)
	FastScrollView fastScrollView;
	@ViewById(R.id.specific_shoplist)
	ListView shopListView;
	private List<ShopItem> shopItems = new ArrayList<ShopItem>();
	private ShopListAdapter shopAdapter;
	private ShopListReq shopListReq = new ShopListReq();
	private ShopItem shopItem;

	private FastScrollView fastScroller; // 快速滚动器
	private IdleListener idleListener; // 空闲监听器
	private IdleListDetector mPostScrollLoader; // 空闲状态解析器

	/** 显示店铺列表 **/
	private int VIEW_SHOPLIST = 1;
	/** 显示断网 **/
	private int VIEW_WIFIFAILUER = 2;
	/** 显示加载数据失败 **/
	private int VIEW_LOADFAILURE = 3;
	/** 显示加载中 **/
	private int VIEW_LOADING = 4;
	/** 显示请求超时 **/
	private int VIEW_OUTTIME = 5;
	/** 显示没有数据 **/
	private int VIEW_NOSHOPS = 6;

	private int pageNext = 1;

	@Override
	public void onResume() {
		super.onResume();
		headTitle.setText("活动店铺");
		getData();
		// 初始化ListView
		initListView(); 
		shopListView.setSelection(0);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void getData() {
		if(hasInfo()){
			Class originClzz = mInfo.getOriginClzz();
			if (originClzz!=null && TextUtils.equals(IndexFragment_.class.getName(), originClzz.getName())) { 
				// 从首页过来的
				defParams();
				List<String> shopList = (List<String>) mInfo.getData();
				String[] shopArr = new String[shopList.size()];
				for (int i = 0; i < shopList.size(); i++) {
					shopArr[i] = shopList.get(i);
				}
				shopListReq.setCodeList(shopArr);
			}
			showViewById(VIEW_LOADING);
			refreshData(true);
		}
	}

	/**初始化listview*/
	private void initListView() {
		if (shopAdapter == null) {
			shopAdapter = new ShopListAdapter(shopItems, mContext);
			shopListView.setAdapter(shopAdapter);
			setupIdleListener(shopListView);
		}
		// 监听ListView滚动
		fastScrollView.setScrollListener(new DefScrollListener(shopItems, mContext, new DefScrollCallBack() {
			@Override
			public void callBack() {
				showProgressDialog();
				refreshData(false);
			}
		}));
	}

	protected void setupIdleListener(AbsListView list) {
		idleListener = new IdleListener(list, 0);
		mPostScrollLoader = new IdleListDetector(idleListener);
		fastScroller = (FastScrollView) list.getParent();
		fastScroller.setOnIdleListDetector(mPostScrollLoader);
	}

	@Click(R.id.myback)
	void exitFm() {
		finish();
	}

	@ItemClick(R.id.specific_shoplist)
	public void shopListItemClick(int position) {
		shopItem = shopItems.get(position);
		Info<ShopItem> info = new Info<ShopItem>();
		info.setData(shopItem);
		info.setOrigin(SpecificShopsActivity_.class);
		openActivity(ShopInfoActivity.class, info);
		finish();
	}

	private void refreshData(boolean clean) {
		lastTask = new RefreshDataTask(lastTask.getID() + 1, clean);
		executeTask(lastTask);
	}

	/**
	 * 丢弃老数据重新刷新
	 * 
	 * @author longtao.li
	 * 
	 */
	class RefreshDataTask extends Task {

		boolean flag = false; // 是否清空原数据

		public RefreshDataTask(int id, boolean flag) {
			super(id);
			this.flag = flag;
		}

		@Override
		public void run() {
			if (!NetWorkCenter.isNetworkConnected(mContext)) { // 断网

				showViewById(VIEW_WIFIFAILUER);
				return;
			}

			if (pageNext == 0) {
				dismissProgressDialog();
				return;
			}

			CodeListResult<ShopItem> result = null;
			try {
				if (LocationLoopService.getInstance(mContext).getChosenAddr() != null) {
					shopListReq.setLat(LocationLoopService.getInstance(mContext).getChosenAddr().getLat());
					shopListReq.setLng(LocationLoopService.getInstance(mContext).getChosenAddr().getLng());
				} else {
					if (mBaiduLocationService.getLastLocation() != null) {
						shopListReq.setLat(mBaiduLocationService.getLastLocation().getLatitude() + "");
						shopListReq.setLng(mBaiduLocationService.getLastLocation().getLongitude() + "");
					}
				}
				shopListReq.setKey("");
				shopListReq.setScope(""); // 店铺类型
				shopListReq.setSortType(""); // 排序字段 1-按照距离 2-起送价最低 3-销量最高
				shopListReq.setPage(pageNext); // 页号
				// shopListReq.setCodeList(new String[]{}); //店铺编号列表
				result = mShopsModel.v2_3queryShopList(shopListReq);
			} catch (RetrofitError e) {
				switch (e.getKind()) {
				case HTTP:
					showViewById(VIEW_OUTTIME);
					break;
				case CONVERSION:
					showViewById(VIEW_LOADFAILURE);
					break;
				case NETWORK:
					showViewById(VIEW_OUTTIME);
					break;
				case UNEXPECTED:
					showViewById(VIEW_LOADFAILURE);
					break;
				}
			} finally {
				dismissProgressDialog();
			}

			// 判断是不是用户的最后操作,最后任务的ID如果比此任务的ID大则丢弃请求结果
			if (getID() < lastTask.getID()) {
				return;
			}

			if (result != null && result.code == 1) {
				refreshUI(result, flag);
			} else {
				showViewById(VIEW_LOADFAILURE);
			}

		}

	}

	@UiThread
	void refreshUI(CodeListResult<ShopItem> result, boolean flag) {
		List<ShopItem> list = result.getList();

		if (list == null || list.size() == 0) {// 没有数据返回
			shopItems.clear();
			shopAdapter.notifyDataSetChanged();
			showViewById(VIEW_NOSHOPS);
		} else {
			showViewById(VIEW_SHOPLIST);
			if (!flag) { // 有数据返回
				pageNext = result.page;
				shopItems.addAll(list);
				shopAdapter.notifyDataSetChanged();
			} else { // 有数据返回但需要回到顶部
				shopItems.clear();
				pageNext = result.page;
				shopItems.addAll(list);
				shopAdapter.notifyDataSetChanged();
				shopListView.setSelection(0);
			}
		}

	}

	/**
	 * 显示店铺列表：1 显示断网：2 显示加载数据失败：3 显示加载中：4 显示请求超时：5 显示没有数据：6
	 */
	@UiThread
	void showViewById(int i) {
		shopListView.setVisibility(View.GONE);
		mErrorHintView.setVisibility(View.GONE);
		switch (i) {
		case 1:
			mErrorHintView.hideLoading();
			shopListView.setVisibility(View.VISIBLE);
			break;

		case 2:
			mErrorHintView.hideLoading();
			mErrorHintView.netError(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					refreshData(true);
				}
			});
			break;

		case 3:
			mErrorHintView.hideLoading();
			mErrorHintView.loadFailure(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					refreshData(true);
				}
			});
			break;

		case 4:
			mErrorHintView.loadingData();
			break;

		case 5:
			mErrorHintView.hideLoading();
			mErrorHintView.timeOut(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					refreshData(true);
				}
			});
			break;

		case 6:
			mErrorHintView.hideLoading();
			mErrorHintView.noShops("附近没有此类店铺");
			break;
		}
	}

	/**
	 * 恢复默认搜索状态
	 */
	private void defParams() {
		pageNext = 1;
		shopListReq.setPage(1);
		shopListReq.setKey("");
		shopListReq.setScope("");
		shopListReq.setSortType("");
	}

	@Override
	public boolean backOperate() {
		return false;
	}
	

}
